package com.rongke.web.controller.util;

import com.alibaba.fastjson.JSONObject;
import com.rongke.commons.JsonResp;
import com.rongke.model.OperationRecord;
import com.rongke.service.OperationRecordService;
import com.rongke.utils.DateUtils;
import com.rongke.utils.IdCardCheck;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jodd.util.StringUtil;

/**
 * 身份证姓名校验接口
 * 
 * @version : Ver 1.0
 */
@RestController
public class IdCardCheckController {
	private static final Logger LOGGER = Logger
			.getLogger(IdCardCheckController.class);

	@Autowired
	private OperationRecordService operationRecordService;

	@RequestMapping(value = "/api/idcardCheck", method = RequestMethod.GET)
	public JsonResp idCardCheck(String idCardNo, String name) {

		try {
			LOGGER.debug("idCardCheck");

			String validIdCardNo = IdCardCheck.checkValidIdCardNo(idCardNo);
			if (StringUtil.isEmpty(validIdCardNo)) {
				LOGGER.error("Invalid idCardNo=" + idCardNo);
				return JsonResp.fa("身份证格式不正确");
			}

			// TODO:身份证姓名校验接口

			String birthday = IdCardCheck.getBirthday(validIdCardNo);
			int sex = IdCardCheck.getSex(validIdCardNo).ordinal();

			String birthYear = birthday.substring(0, 4);
			String currentYear = DateUtils.getCurrentTime().substring(0, 4);
			int age = Integer.parseInt(currentYear)
					- Integer.parseInt(birthYear);
			if (age == 0) {
				age = 1;
			}

			JSONObject json = new JSONObject();
			json.put("idCardCheck", true);
			json.put("birthday", birthday);
			json.put("sex", sex);
			json.put("idCardNo", validIdCardNo);
			json.put("age", age);

			return JsonResp.ok(json);
		} catch (Exception e) {
			LOGGER.error("idCardCheck failed", e);
			return JsonResp.fa(null);
		}
	}
}
